#!/bin/bash

timestamp() {
  res=$(date "+%Y-%m-%d %H:%M:%S")
  echo $res
}

timestamp::to_seconds() {
  local text=$@
  if [ -z "$text" ]; then
    log::error "[timestamp::to_seconds] timestamp string is required"
    exit 1
  fi

  if [ "$(os::is_macos)" = "true" ]; then
    date -jf "%Y-%m-%d %H:%M:%S" "$text" +%s
    return
  fi

  date -d "$text" +%s
}

timestamp::gt() {
  local a=$1
  local b=$2

  echo "a: $a"
  echo "b: $b"

  if [ $a -gt $b ]; then
    echo "true"
  else
    echo "false"
  fi
}

timestamp::lt() {
  local a=$1
  local b=$2

  if [ $a -lt $b ]; then
    echo "true"
  else
    echo "false"
  fi
}

# in x minutes
# example: 5 2021-09-05 11:30:10
# example: 5 1630824627
timestamp::in_x_minutes() {
  local x_minutes=$1
  local text=${@:2}

  if [ -z "$x_minutes" ]; then
    log::error "[timestamp::recently] x_minutes is required"
    exit 1
  fi

  if [ -z "$text" ]; then
    log::error "[timestamp::recently] timestamp string | numver is required"
    exit 1
  fi

  local x_seconds=$((60 * $x_minutes))
  local ts=$text

  echo $text | grep ":" >>/dev/null 2>&1
  if [ "$?" = "0" ]; then
    ts=$(timestamp::to_seconds $text)
  fi

  local now=$(date +%s)
  local ts_5m_later=$(($ts + $x_seconds))

  timestamp::lt $now $ts_5m_later
}

# in 5 minutes
timestamp::recently() {
  timestamp::in_x_minutes 5 $@
}

export -f timestamp
export -f timestamp::to_seconds
export -f timestamp::gt
export -f timestamp::lt
export -f timestamp::in_x_minutes
export -f timestamp::recently
